﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TrainSimulator.Model;
using TrainSimulator.Interfaces;

namespace TrainSimulator.State
{
    internal class TrainAccelerating : State
    {
        public TrainAccelerating()
        {
            base._description = "Accelerating";
        }

        public override IState Handle(ITrain train)
        {
            IState stateResult = null;
            Console.WriteLine(train.Speed);
            // if speed is faster than requested speed
            if (Math.Abs(train.Speed - train.RequestedSpeed) > 0.2)
            {
                double acceleration = Math.Abs(train.RequestedSpeed - train.Speed) / 2;
                if (train.Speed > train.RequestedSpeed)
                {
                    if (train.Engine.Deacceleration < acceleration)
                        acceleration = -train.Engine.Deacceleration;
                    else
                        acceleration = -acceleration;
                }
                else
                {
                    if (train.Engine.Accelerating < acceleration)
                        acceleration = train.Engine.Accelerating;
                    // else acceleration stays the same
                }
                train.Engine.Accelerating = acceleration;
                stateResult = this;
            }
            else
            {
                train.Engine.Accelerating = 0;
                train.Speed = train.RequestedSpeed;
                stateResult = train.PreviousState;
            }
            return stateResult;
        }
    }
}
